/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

CppSourceNode::CppSourceNode(BuildGraph* graph, string fname, string arch)
	: BuildGraphNode(graph)
	, m_fname(fname)
	, m_arch(arch)
{
	
}

CppSourceNode::~CppSourceNode()
{
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

string CppSourceNode::GetOutputPath()
{
	return m_fname;
}

string CppSourceNode::GetBinaryPath()
{
	return m_fname;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency scanning

string CppSourceNode::GetHash()
{
	//DebugPrintfHeading(1, "CppSourceNode::GetHash()\n");
	//DebugPrintfSilent(1, "    source file %s\n", m_fname.c_str());
	
	//Get hash of our dependencides
	string hash = sha256_file(m_fname);
	hash += sha256(m_arch);
	
	//Add data for our dependencies
	for(size_t i=0; i<m_dependencies.size(); i++)
		hash += m_dependencies[i]->GetHashCached(); 
			
	//Done
	return sha256(hash);
}

void CppSourceNode::UpdateDependencies()
{
	//Unless automatically generated (handled by derived class), no dependencies exist.
	//Headers, etc are used to build an object file, not a source file, so they're not meaningful dependencies here.
}

string CppSourceNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "C++ source %s [%s]", GetBasenameOfFile(m_fname).c_str(), m_arch.c_str());
	return string(desc);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Compilation

void CppSourceNode::Update(Cluster* cluster)
{
	//Rebuild our dependencies (in case any header files were auto-generated, etc)
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Create a null cluster job that depends on all of these, to ensure proper blocking order
	if(deps.size() != 0)
	{
		string path = m_graph->GetMetaDir() + "/" + GetHashCached();
		string base = GetBasenameOfFileWithoutExt(m_fname);
		
		string batch_fname = path + "/" + base + "_nop.sh";
		FILE* fp = fopen(batch_fname.c_str(), "w");
		if(!fp)
			FatalError("Failed to create batch script %s\n", batch_fname.c_str());
		fprintf(fp, "#!/bin/bash\n");
		fprintf(fp, "touch build_successful\n");
		fclose(fp);
		if(0 != chmod(batch_fname.c_str(), 0755))
			FatalError("Failed to set execute permissions on batch script %s\n", batch_fname.c_str());
			
		m_job = cluster->SubmitBatchJob(batch_fname, cluster->m_cppBuildPartition, path, deps);
	}
}
